package com.yiyiooo.Abp.basics;

import android.util.Log;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.yiyiooo.client.invoker.ApiException;
import com.squareup.okhttp.Interceptor;
import com.squareup.okhttp.MediaType;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;
import com.squareup.okhttp.ResponseBody;

import java.io.IOException;

import okio.BufferedSource;

public class AbpInterceptors implements Interceptor {
    // 请不要直接修改 apiErrorHandel 内的实现，请在别的地方覆盖 apiErrorHandel
    public ApiErrorHandel apiErrorHandel = new ApiErrorHandel() {
        @Override
        public void handelError(Response response) {
            Log.e("ApiErrorHandel",response.message());
        }

        @Override
        public void handelSuccess(Response response) {
            Log.i("ApiErrorHandel",response.message());
        }
    };

    static public Response copyRepose(Response response,byte[] body){
        return new Response.Builder()
                .code(response.code())
                .message(response.message())
                .request(response.request())
                .headers(response.headers())
                .protocol(response.protocol())
                .handshake(response.handshake())
                .body(ResponseBody.create(response.body().contentType(),body))
                .build();
    }
    @Override
    public Response intercept(Chain chain) throws IOException {
        Request request = chain.request();
        Request compressedRequest = request.newBuilder()
                .header("X-Requested-With","XMLHttpRequest")
                .header("Abp.TenantId",AbpSession.getInstance().getTenantId())
                .header("Abp-TenantId",AbpSession.getInstance().getTenantId())
                .header(".AspNetCore.Culture","zh")
                .header("Accept-Language","zh")
                .header("Authorization","Bearer "+AbpSession.getInstance().getAccessToken())
                .method(request.method(), request.body())
                .build();
        Log.d("AbpInterceptors","Request TenantId:"+compressedRequest.header("Abp.TenantId"));

        Response response = null;
        byte[] body = {};
        try{
            response = chain.proceed(compressedRequest);
            // 因为统一错误处理会读取reposeBody里面的内容，又因为这个内容只能被读取一次，所以此处复制了一次；
            body = response.body().bytes();
            response = copyRepose(response,body);

            if(response.code()>=400) {
                apiErrorHandel.handelError(response);
            }
            else if(response.code()>=200) {
                apiErrorHandel.handelSuccess(response);
            };
            if(response.code()==200){
                // 因为abp后台返回的数据类型额外包裹了一层，此处需要去掉这一层才能成为api处理函数需要的数据格式
                JSONObject resultBody = (JSONObject) JSON.toJavaObject(JSON.parseObject(copyRepose(response,body).body().string()),AbpResultDto.class).result;
                String jsonBody = resultBody.toJSONString();
                body = jsonBody.getBytes("utf-8");
            }
        }catch (IOException ex){
            Log.e("AbpInterceptors",ex.getMessage());
            response = new Response.Builder().code(502).message(ex.getMessage()).body(null).request(request).build();
            apiErrorHandel.handelError(response);
        }catch (Exception ex){
            Log.e("AbpInterceptors",ex.getMessage());
        }
        return copyRepose(response,body);
    }
    public interface ApiErrorHandel{
        void handelError(Response response);
        void handelSuccess(Response response);
    }
}
